package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.FlowElementProcessContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.CustomPropertiesProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.FlowActivityApproverVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowActivityAproverRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: niechanggang
 * @date:2021/9/1 23:56
 * @description:
 */
@Service
public class SaveActivityApproverProcessor  implements CustomPropertiesProcessor {

    private Logger  logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FlowActivityAproverRepository flowActivityAproverRepository;

    @Override
    public boolean support(JsonNode elementNode) {
        JsonNode properties = elementNode.get("properties");
        if (nonNull(properties)) {
            JsonNode candidateUsers = properties.get("candidateUsers");
            return nonNull(candidateUsers);
        }
        return false;
    }

    @Override
    public void process(FlowElementProcessContext context) {
        String deployId = context.getDeployId();
        String activityId = context.getNodeCode();
        JsonNode elementNode = context.getElementNode();
        JsonNode properties = elementNode.get("properties");
        if(properties == null){
            return ;
        }
        JsonNode candidateUsers = properties.get("candidateUsers");
        Date date = new Date();
        for(int i =0; i<candidateUsers.size();i++){
            JsonNode candidateUser = candidateUsers.get(i);
            String code = candidateUser.get("code").textValue();
            String name = candidateUser.get("name").textValue();
            String type = candidateUser.get("type").textValue();
            if("VAR".equals(type)){
                continue;
            }
            FlowActivityApproverVo flowActivityApproverVo = new FlowActivityApproverVo();
            flowActivityApproverVo.setDeployId(deployId);
            flowActivityApproverVo.setActivityId(activityId);
            flowActivityApproverVo.setCode(code);
            flowActivityApproverVo.setName(name);
            flowActivityApproverVo.setType(type);
            flowActivityApproverVo.setCreateTime(date);
            flowActivityAproverRepository.insert(flowActivityApproverVo);
        }
    }
}
